package cn.com.twoke.game.client.handler;

import cn.com.twoke.game.client.cache.ClientCacheManager;
import cn.com.twoke.game.client.games.GameConfig;
import cn.com.twoke.game.client.games.GameManager;
import cn.com.twoke.game.client.games.framework.core.Game;
import cn.com.twoke.game.client.ui.UiManager;
import cn.com.twoke.game.common.entity.message.StartGameMessage;
import cn.com.twoke.game.common.handler.MessageHandler;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class StartGameMessageHandler implements MessageHandler<StartGameMessage> {

    @Override
    public void handle(Selector selector, SocketChannel channel, StartGameMessage message) throws IOException {
        UiManager.WINDOW.dispose();
        Game game = GameManager.GAMES.stream().filter(item -> item.getId().equals(message.getGameId()))
                .findFirst().get().getGame().apply(new GameConfig.CreateGameContext(message.getPlayerCount()));
        game.setRoomMaster(message.getRoomMasterId().equals(ClientCacheManager.INSTANCE.getUsername()));
        game.setRoomId(message.getRoomId());
        game.setPlayerName(ClientCacheManager.INSTANCE.getUsername());
        game.setNetwork(true);
        game.initGameState();
        ClientCacheManager.INSTANCE.registerGame(message.getGameId(), game);
        game.show();
    }


}
